/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package at.tugraz.hidipic.upload;

import at.tugraz.hidipic.model.DataItem;
import at.tugraz.hidipic.model.InputDataItem;
import at.tugraz.hidipic.model.User;
import java.io.*;
import java.util.Date;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author mario
 */
public class UploadService {

    private final Logger LOG = Logger.getLogger(UploadService.class);
    @Autowired
    private HibernateTemplate hibernateTemplate;

    /**
     * save the file and call persistance
     *
     * @param file
     * @param path
     * @param name
     * @param creator
     * @param type
     * @param extension
     * @return json string for the frontpage
     * @throws IOException
     */
    public String saveFile(MultipartFile file, String path, String name, User creator, String type, String extension) throws IOException {
        try {
            if (type != null && extension != null) {
                UUID uuid = UUID.randomUUID();
                Long randsuffix = uuid.getMostSignificantBits();
                String filen = "f" + randsuffix.toString() + "." + extension;
                File filePath = new File(path);
                if (filePath.exists()) {
                    InputStream i = file.getInputStream();
                    OutputStream o = new FileOutputStream(path + filen); //new filename
                    byte[] buffer = file.getBytes();
                    int bytesread;
                    while ((bytesread = i.read(buffer)) != - 1) {
                        o.write(buffer, 0, bytesread);
                        o.flush();
                    }
                    o.close();
                    i.close();
                    createMediaEntry(path, filen, name, creator, type);
                    return "/KNODWAT/dynamicimages/" + filen;
                }
            }
        } catch (Exception e) {
            LOG.error(e);
        }
        return null;
    }

    /**
     * persist file to database
     * @param path
     * @param file
     * @param name
     * @param creator
     * @param type
     */
    private void createMediaEntry(String path, String file, String name, User creator, String type) {
        InputDataItem media = new InputDataItem();
        media.setCreated(new Date());
        media.setUrl("/dynamicimages/" + file);
        media.setName(file);
        media.setTitle(name);
        media.setCreator(creator);
        media.setType(type);
        hibernateTemplate.saveOrUpdate(media);
    }
}
